<template>
  <view class="page-container">
    <!-- 导航栏：返回按钮+标题 横向对齐 -->
    <!-- 自定义导航栏（替代 tn-nav-bar） -->
        <view class="custom-nav-bar">
          <!-- 返回按钮 -->
          <view class="nav-back-btn" @click="goBack">
            <text class="icon tn-icon-left"></text>
          </view>
          <!-- 标题 -->
          <view class="nav-title">返校信息登记表</view>
        </view>

    <!-- 主内容区：滚动布局，避免内容溢出 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 表单说明文本 -->
      <view class="form-desc">请填写以下信息完成登记</view>
      
      <!-- 表单卡片：居中显示，限制最大宽度 -->
      <view class="form-card">
        <form @submit.prevent="handleSubmit">
          <!-- 主手机号 -->
          <view class="form-group">
            <label class="form-label">手机号</label>
            <input 
              type="tel" 
              class="form-input" 
              v-model="formData.phoneNo" 
              placeholder="请输入您的手机号"
            />
          </view>
          
          <!-- 返校人数 -->
          <view class="form-group">
            <label class="form-label">返校人数</label>
            <input 
              type="number" 
              class="form-input" 
              v-model="formData.peopleCount" 
              placeholder="请输入同行返校人数（含本人）"
              min="1"
            />
          </view>
          
          <!-- 返校时间选择 -->
          <view class="form-group">
            <label class="form-label">返校时间</label>
            <view class="picker-wrap" @click="showReturnPicker = true">
              <input 
                type="text" 
                class="form-input picker-input" 
                :value="formData.returnTime" 
                readonly
                placeholder="请选择返校时间"
              />
              <view class="picker-arrow">▼</view>
            </view>
          </view>
          
          <!-- 返校时间选择器 -->
          <view class="picker-overlay" v-if="showReturnPicker" @click="showReturnPicker = false">
            <view class="picker-modal" @click.stop>
              <view class="picker-toolbar">
                <button class="picker-btn cancel" @click="showReturnPicker = false">取消</button>
                <button class="picker-btn confirm" @click="confirmReturnTime">确定</button>
              </view>
              <picker-view 
                class="picker-view"
                :indicator-style="indicatorStyle"
                @change="handleReturnPickerChange"
              >
                <picker-view-column><view v-for="y in returnValidYears" :key="y">{{ y }}年</view></picker-view-column>
                <picker-view-column><view v-for="m in getReturnValidMonths()" :key="m">{{ padZero(m) }}月</view></picker-view-column>
                <picker-view-column><view v-for="d in getReturnValidDays()" :key="d">{{ padZero(d) }}日</view></picker-view-column>
                <picker-view-column><view v-for="h in getReturnValidHours()" :key="h">{{ padZero(h) }}时</view></picker-view-column>
                <picker-view-column><view v-for="min in getReturnValidMinutes()" :key="min">{{ padZero(min) }}分</view></picker-view-column>
              </picker-view>
            </view>
          </view>
          
          <!-- 离校时间选择 -->
          <view class="form-group">
            <label class="form-label">离校时间</label>
            <view class="picker-wrap" @click="formData.returnTime ? showLeavePicker = true : showToast('请先选择返校时间')">
              <input 
                type="text" 
                class="form-input picker-input" 
                :value="formData.leaveTime" 
                readonly
                placeholder="请先选择返校时间"
              />
              <view class="picker-arrow">▼</view>
            </view>
          </view>
          
          <!-- 离校时间选择器 -->
          <view class="picker-overlay" v-if="showLeavePicker" @click="showLeavePicker = false">
            <view class="picker-modal" @click.stop>
              <view class="picker-toolbar">
                <button class="picker-btn cancel" @click="showLeavePicker = false">取消</button>
                <button class="picker-btn confirm" @click="confirmLeaveTime">确定</button>
              </view>
              <picker-view 
                class="picker-view"
                :indicator-style="indicatorStyle"
                @change="handleLeavePickerChange"
              >
                <picker-view-column><view v-for="y in leaveValidYears" :key="y">{{ y }}年</view></picker-view-column>
                <picker-view-column><view v-for="m in getLeaveValidMonths()" :key="m">{{ padZero(m) }}月</view></picker-view-column>
                <picker-view-column><view v-for="d in getLeaveValidDays()" :key="d">{{ padZero(d) }}日</view></picker-view-column>
                <picker-view-column><view v-for="h in getLeaveValidHours()" :key="h">{{ padZero(h) }}时</view></picker-view-column>
                <picker-view-column><view v-for="min in getLeaveValidMinutes()" :key="min">{{ padZero(min) }}分</view></picker-view-column>
              </picker-view>
            </view>
          </view>
          
          <!-- 返校活动选择 -->
          <view class="form-group">
            <label class="form-label">返校活动</label>
            <select 
              class="form-select" 
              v-model="formData.activity"
            >
              <option value="" disabled selected>请选择返校活动</option>
              <option value="academic">学术交流</option>
              <option value="reunion">同学聚会</option>
              <option value="ceremony">毕业典礼</option>
              <option value="other">其他活动</option>
            </select>
          </view>
          
          <!-- 提交按钮 -->
          <view class="form-actions">
            <button 
              type="submit" 
              class="submit-btn"
              :disabled="isSubmitting"
            >
              <template v-if="isSubmitting">
                <view class="loading-spinner"></view>
                <span>提交中...</span>
              </template>
              <template v-else>
                提交信息
              </template>
            </button>
          </view>
        </form>
      </view>
    </scroll-view>
    
    <!-- 提交成功弹窗 -->
    <view class="success-modal" v-if="showSuccess">
      <view class="modal-content">
        <view class="success-icon">✓</view>
        <h3>提交成功！</h3>
        <p>您的返校信息已成功提交</p>
        <button class="modal-btn" @click="showSuccess = false">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    const now = new Date();
    return {
      formData: {
        phoneNo: '',
        peopleCount: '',
        returnTime: '',
        leaveTime: '',
        activity: ''
      },
      indicatorStyle: 'height: 80rpx;',
      months: [1,2,3,4,5,6,7,8,9,10,11,12],
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1,
      currentDay: now.getDate(),
      currentHour: now.getHours(),
      currentMinute: now.getMinutes(),
      
      showReturnPicker: false,
      returnSelYear: now.getFullYear(),
      returnSelMonth: now.getMonth() + 1,
      returnSelDay: now.getDate(),
      returnSelHour: now.getHours(),
      returnSelMinute: now.getMinutes(),
      returnValidYears: [],
      
      showLeavePicker: false,
      leaveSelYear: now.getFullYear(),
      leaveSelMonth: now.getMonth() + 1,
      leaveSelDay: now.getDate(),
      leaveSelHour: now.getHours() + 1,
      leaveSelMinute: now.getMinutes(),
      leaveValidYears: [],
      
      isSubmitting: false,
      showSuccess: false
    };
  },
  created() {
    this.returnValidYears = Array.from({length: 2026 - this.currentYear + 1}, (_,i)=>this.currentYear + i);
    this.leaveValidYears = [...this.returnValidYears];
    this.resetReturnDefault();
    this.resetLeaveDefault();
  },
  methods: {
    goBack() {
      uni.navigateBack({
        delta: 1,
        fail: () => {
          uni.closeCurrentPages();
        }
      });
    },
    padZero(num) {
      const n = Number(num);
      return isNaN(n) ? '00' : (n < 10 ? '0' + n : n.toString());
    },
    getDays(year, month) {
      if (!year || !month || month < 1 || month > 12) return 31;
      return new Date(year, month, 0).getDate();
    },
    resetReturnDefault() {
      const now = new Date();
      this.returnSelYear = now.getFullYear();
      this.returnSelMonth = now.getMonth() + 1;
      this.returnSelDay = now.getDate();
      this.returnSelHour = now.getHours();
      this.returnSelMinute = now.getMinutes();
    },
    resetLeaveDefault() {
      if (!this.formData.returnTime) {
        const defaultTime = new Date();
        defaultTime.setHours(defaultTime.getHours() + 1);
        this.leaveSelYear = defaultTime.getFullYear();
        this.leaveSelMonth = defaultTime.getMonth() + 1;
        this.leaveSelDay = defaultTime.getDate();
        this.leaveSelHour = defaultTime.getHours();
        this.leaveSelMinute = defaultTime.getMinutes();
        return;
      }
      const returnDate = new Date(this.formData.returnTime.replace(' ', 'T'));
      returnDate.setHours(returnDate.getHours() + 1);
      this.leaveSelYear = returnDate.getFullYear();
      this.leaveSelMonth = returnDate.getMonth() + 1;
      this.leaveSelDay = returnDate.getDate();
      this.leaveSelHour = returnDate.getHours();
      this.leaveSelMinute = returnDate.getMinutes();
    },
    getReturnValidMonths() {
      if (this.returnSelYear > this.currentYear) {
        return [...this.months];
      }
      return this.months.filter(m => m >= this.currentMonth);
    },
    getReturnValidDays() {
      const maxDay = this.getDays(this.returnSelYear, this.returnSelMonth);
      if (this.returnSelYear !== this.currentYear || this.returnSelMonth !== this.currentMonth) {
        return Array.from({length: maxDay}, (_,i)=>i+1);
      }
      const validDays = Array.from({length: maxDay - this.currentDay + 1}, (_,i)=>this.currentDay + i);
      return validDays.length > 0 ? validDays : [this.currentDay];
    },
    getReturnValidHours() {
      if (this.returnSelYear !== this.currentYear || this.returnSelMonth !== this.currentMonth || this.returnSelDay !== this.currentDay) {
        return Array.from({length:24}, (_,i)=>i);
      }
      const validHours = Array.from({length:24 - this.currentHour}, (_,i)=>this.currentHour + i);
      return validHours.length > 0 ? validHours : [this.currentHour];
    },
    getReturnValidMinutes() {
      if (this.returnSelYear !== this.currentYear || this.returnSelMonth !== this.currentMonth || this.returnSelDay !== this.currentDay || this.returnSelHour !== this.currentHour) {
        return Array.from({length:60}, (_,i)=>i);
      }
      const validMinutes = Array.from({length:60 - this.currentMinute}, (_,i)=>this.currentMinute + i);
      return validMinutes.length > 0 ? validMinutes : [this.currentMinute];
    },
    handleReturnPickerChange(e) {
      const [yIdx, mIdx, dIdx, hIdx, minIdx] = e.detail.value;
      this.returnSelYear = this.returnValidYears[yIdx] || this.returnValidYears[0];
      const validMonths = this.getReturnValidMonths();
      this.returnSelMonth = validMonths[mIdx] || validMonths[0];
      const validDays = this.getReturnValidDays();
      this.returnSelDay = validDays[dIdx] || validDays[0];
      const validHours = this.getReturnValidHours();
      this.returnSelHour = validHours[hIdx] || validHours[0];
      const validMinutes = this.getReturnValidMinutes();
      this.returnSelMinute = validMinutes[minIdx] || validMinutes[0];
    },
    getLeaveValidMonths() {
      if (!this.formData.returnTime) return [];
      if (this.leaveSelYear > this.returnSelYear) {
        return [...this.months];
      }
      const validMonths = this.months.filter(m => m >= this.returnSelMonth);
      return validMonths.length > 0 ? validMonths : [this.returnSelMonth];
    },
    getLeaveValidDays() {
      if (!this.formData.returnTime) return [];
      const maxDay = this.getDays(this.leaveSelYear, this.leaveSelMonth);
      if (this.leaveSelYear !== this.returnSelYear || this.leaveSelMonth !== this.returnSelMonth) {
        return Array.from({length: maxDay}, (_,i)=>i+1);
      }
      const validDays = Array.from({length: maxDay - this.returnSelDay + 1}, (_,i)=>this.returnSelDay + i);
      return validDays.length > 0 ? validDays : [this.returnSelDay];
    },
    getLeaveValidHours() {
      if (!this.formData.returnTime) return [];
      if (this.leaveSelYear !== this.returnSelYear || this.leaveSelMonth !== this.returnSelMonth || this.leaveSelDay !== this.returnSelDay) {
        return Array.from({length:24}, (_,i)=>i);
      }
      const validHours = Array.from({length:24 - this.returnSelHour}, (_,i)=>this.returnSelHour + i);
      return validHours.length > 0 ? validHours : [this.returnSelHour];
    },
    getLeaveValidMinutes() {
      if (!this.formData.returnTime) return [];
      if (this.leaveSelYear !== this.returnSelYear || this.leaveSelMonth !== this.returnSelMonth || this.leaveSelDay !== this.returnSelDay || this.leaveSelHour !== this.returnSelHour) {
        return Array.from({length:60}, (_,i)=>i);
      }
      const validMinutes = Array.from({length:60 - this.returnSelMinute}, (_,i)=>this.returnSelMinute + i);
      return validMinutes.length > 0 ? validMinutes : [this.returnSelMinute];
    },
    handleLeavePickerChange(e) {
      const [yIdx, mIdx, dIdx, hIdx, minIdx] = e.detail.value;
      this.leaveSelYear = this.leaveValidYears[yIdx] || this.leaveValidYears[0];
      const validMonths = this.getLeaveValidMonths();
      this.leaveSelMonth = validMonths[mIdx] || validMonths[0];
      const validDays = this.getLeaveValidDays();
      this.leaveSelDay = validDays[dIdx] || validDays[0];
      const validHours = this.getLeaveValidHours();
      this.leaveSelHour = validHours[hIdx] || validHours[0];
      const validMinutes = this.getLeaveValidMinutes();
      this.leaveSelMinute = validMinutes[minIdx] || validMinutes[0];
    },
    confirmReturnTime() {
      const year = Number(this.returnSelYear);
      const month = Number(this.returnSelMonth);
      const day = Number(this.returnSelDay);
      const hour = Number(this.returnSelHour);
      const minute = Number(this.returnSelMinute);
      this.formData.returnTime = `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}`;
      this.showReturnPicker = false;
      this.resetLeaveDefault();
    },
    confirmLeaveTime() {
      const year = Number(this.leaveSelYear);
      const month = Number(this.leaveSelMonth);
      const day = Number(this.leaveSelDay);
      const hour = Number(this.leaveSelHour);
      const minute = Number(this.leaveSelMinute);
      this.formData.leaveTime = `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}`;
      this.showLeavePicker = false;
    },
    showToast(title) {
      uni.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      });
    },
    handleSubmit() {
      // 手机号校验
      if (!this.formData.phoneNo.trim()) return this.showToast('请输入手机号');
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.formData.phoneNo.trim())) return this.showToast('请输入正确的手机号');
      
      // 返校人数校验
      if (!this.formData.peopleCount.trim()) return this.showToast('请输入返校人数');
      if (Number(this.formData.peopleCount) < 1) return this.showToast('返校人数不能少于1人');
      
      // 时间校验
      if (!this.formData.returnTime) return this.showToast('请选择返校时间');
      if (!this.formData.leaveTime) return this.showToast('请选择离校时间');
      const returnDate = new Date(this.formData.returnTime.replace(' ', 'T')).getTime();
      const leaveDate = new Date(this.formData.leaveTime.replace(' ', 'T')).getTime();
      if (returnDate >= leaveDate) return this.showToast('返校时间不能晚于离校时间');
      
      // 活动校验
      if (!this.formData.activity) return this.showToast('请选择返校活动');
      
      // 提交逻辑
      this.isSubmitting = true;
      setTimeout(() => {
        this.isSubmitting = false;
        this.showSuccess = true;
        // 重置表单
        const now = new Date();
        this.formData = {
          phoneNo: '',
          peopleCount: '',
          returnTime: '',
          leaveTime: '',
          activity: ''
        };
        this.resetReturnDefault();
        this.resetLeaveDefault();
      }, 1500);
    }
  }
};
</script>

<style scoped>
/* 自定义导航栏样式 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8faf7; /* 与页面背景一致，或透明 */
}

/* 返回按钮：自然居左，不偏移 */
.nav-back-btn {
  width: 70rpx;
  height: 50rpx;
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 100rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  color: #FFFFFF;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  left: 20rpx; /* 仅留左侧间距，不硬编码偏移 */
}

/* 导航栏标题：居中显示，与返回按钮同一水平线 */
.nav-title {
  font-size: 34rpx;
  color: #2d7d46;
  font-weight: 600;
}

/* 滚动内容区：避开导航栏，可滚动 */
.content-scroll {
  width: 100%;
  height: calc(100vh - 90rpx); /* 高度 = 屏幕高度 - 导航栏高度 */
  margin-top: 90rpx; /* 顶部间距 = 导航栏高度，避免内容被遮挡 */
  padding: 30rpx 20rpx;
  box-sizing: border-box;
}

/* 表单说明文本：居中，增强视觉引导 */
.form-desc {
  text-align: center;
  font-size: 26rpx;
  color: #4a9d64;
  margin-bottom: 40rpx;
}

/* 表单卡片：居中，限制最大宽度，增强阴影 */
.form-card {
  width: 100%;
  max-width: 650rpx; /* 平板上不超宽 */
  margin: 0 auto; /* 水平居中 */
  background-color: #fff;
  border-radius: 24rpx;
  padding: 50rpx 30rpx;
  box-shadow: 0 15rpx 40rpx rgba(74, 157, 100, 0.1);
  box-sizing: border-box;
}

/* 表单项间距：统一间距，布局规整 */
.form-group {
  margin-bottom: 40rpx;
}

/* 表单标签：统一样式 */
.form-label {
  display: block;
  font-size: 28rpx;
  color: #2d7d46;
  margin-bottom: 15rpx;
  font-weight: 500;
}

/* 输入框/下拉框：统一尺寸和样式 */
.form-input, .form-select {
  width: 100%;
  height: 88rpx;
  padding: 0 25rpx;
  border: 2rpx solid #e0ebe4;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.form-input:focus, .form-select:focus {
  border-color: #4cd964;
  box-shadow: 0 0 0 6rpx rgba(76, 217, 100, 0.12);
  outline: none;
}

/* 下拉框图标：优化位置 */
.form-select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%234a9d64' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 25rpx center;
  background-size: 32rpx;
}

/* 时间选择器容器：优化交互 */
.picker-wrap {
  position: relative;
}

.picker-input {
  padding-right: 70rpx;
  background-color: #f8faf7;
  cursor: pointer;
}

.picker-arrow {
  position: absolute;
  right: 25rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #4a9d64;
  font-size: 26rpx;
  pointer-events: none;
}

/* 选择器遮罩层：优化层级 */
.picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}

.picker-modal {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  padding-bottom: 20rpx;
}

.picker-toolbar {
  display: flex;
  justify-content: space-between;
  padding: 25rpx 30rpx;
  border-bottom: 1rpx solid #e0ebe4;
}

.picker-btn {
  padding: 15rpx 35rpx;
  font-size: 30rpx;
  border: none;
  background: transparent;
}

.picker-btn.cancel {
  color: #666;
}

.picker-btn.confirm {
  color: #4cd964;
  font-weight: 500;
}

.picker-view {
  width: 100%;
  height: 420rpx;
}

/* 提交按钮区域：优化间距 */
.form-actions {
  margin-top: 60rpx;
}

.submit-btn {
  width: 100%;
  height: 96rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 18rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background-color: #3bc053;
}

.submit-btn:disabled {
  background-color: #b3e6be;
  cursor: not-allowed;
}

/* 加载动画：优化尺寸 */
.loading-spinner {
  width: 36rpx;
  height: 36rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 成功弹窗：优化样式 */
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  width: 85%;
  max-width: 550rpx;
  background-color: #fff;
  border-radius: 24rpx;
  padding: 60rpx 30rpx;
  text-align: center;
  animation: scaleIn 0.3s ease;
  box-shadow: 0 20rpx 50rpx rgba(0, 0, 0, 0.15);
}

.success-icon {
  width: 140rpx;
  height: 140rpx;
  background-color: #4cd964;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 90rpx;
  margin: 0 auto 40rpx;
}

.modal-content h3 {
  font-size: 36rpx;
  color: #2d7d46;
  margin-bottom: 20rpx;
}

.modal-content p {
  font-size: 28rpx;
  color: #4a9d64;
  margin-bottom: 50rpx;
}

.modal-btn {
  width: 100%;
  height: 90rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 30rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}

.modal-btn:hover {
  background-color: #3bc053;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from { transform: scale(0.85); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
</style>